package com.shop.servlet;

import com.shop.model.Student;
import com.shop.service.IStudentService;
import com.shop.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/update_profile")
public class edit_profileServlet extends HttpServlet {
    IStudentService istudentService = new StudentService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        boolean c =false;
        IStudentService istudentService = new StudentService();
        Student student = istudentService.search(req.getParameter("studentId"));


        String name = req.getParameter("name");
        int age = student.getAge();
        int grade = student.getGrade();
        System.out.println("edit_profileServlet:30:" +  age + " " + grade );//调试

        //判断输入的年龄和年级是否是正整数
        if (req.getParameter("age").matches("^[1-9]\\d*$") && req.getParameter("grade").matches("^[1-9]\\d*$")) {
            age = Integer.parseInt(req.getParameter("age"));
            grade = Integer.parseInt(req.getParameter("grade"));
            c = true;
        }
        String major = req.getParameter("major");
        String studentId = req.getParameter("studentId");
        System.out.println("edit_profileServlet:26:" + name + " " + age + " " + grade + " " +major+" "+ studentId);//调试

        Boolean b = istudentService.update(name, age, grade, studentId,major);

        if (b && c) {
            System.out.println("edit_profileServlet：31：修改成功");//调试
            req.setAttribute("error", "修改成功");
            req.getRequestDispatcher("edit_profile.jsp").forward(req, resp);
        } else {
            System.out.println("edit_profileServlet：34：修改失败");//调试
            req.setAttribute("error", "修改失败");
            req.getRequestDispatcher("edit_profile.jsp").forward(req, resp);
        }
    }
}
